package cn.graydove.bot.controller;

import cn.graydove.bot.data.GroupServiceCacheData;
import cn.graydove.bot.model.entity.QqGroup;
import cn.graydove.bot.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Controller
public class ExcelController {

    private GroupServiceCacheData groupServiceCacheData;

    public ExcelController(GroupServiceCacheData groupServiceCacheData) {
        this.groupServiceCacheData = groupServiceCacheData;
    }

    @RequestMapping("/attack/{id}")
    public void attack(HttpServletResponse response, @PathVariable Long id) {
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + tansCode("出刀统计.xls"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        try {
            QqGroup group = groupServiceCacheData.getGroup(id);
            if (group != null) {
                ExcelUtils.genAttackExcel(group.getUsers(), response.getOutputStream());
            }
        } catch (IOException e) {
            log.error("Excel写出IO异常");
        }

    }

    @RequestMapping("/mock/{id}")
    public void mock(HttpServletResponse response, @PathVariable Long id) {
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + tansCode("模拟统计.xls"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        try {
            QqGroup group = groupServiceCacheData.getGroup(id);
            if (group != null) {
                ExcelUtils.genMockExcel(group.getMocks(), response.getOutputStream());
            }
        } catch (IOException e) {
            log.error("Excel写出IO异常");
        }

    }

    private String tansCode(String s) {
        return new String(s.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
    }

}
